import React, { useState, useEffect, useCallback } from 'react';
import { Row, Col, Card, Statistic, Button, List, Tag, Typography, Space, Alert } from 'antd';
import {
  DashboardOutlined,
  UserOutlined,
  ToolOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  SyncOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AppContext';

const { Title, Text } = Typography;

interface DashboardStats {
  totalUsers: number;
  activeTools: number;
  systemHealth: number;
  dailyTasks: number;
}

interface Activity {
  id: number;
  action: string;
  user: string;
  time: string;
  type: string;
}

const Dashboard: React.FC = () => {
  const { user, isAdmin } = useAuth();
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    activeTools: 0,
    systemHealth: 0,
    dailyTasks: 0,
  });
  const [recentActivities, setRecentActivities] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(true);

  const loadDashboardData = useCallback(async () => {
    try {
      // 模拟API调用
      setTimeout(() => {
        setStats({
          totalUsers: 128,
          activeTools: 15,
          systemHealth: 98.5,
          dailyTasks: 245
        });
        
        setRecentActivities([
          { id: 1, action: '用户登录', user: 'admin', time: '2 分钟前', type: 'login' },
          { id: 2, action: '配置更新', user: 'operator', time: '10 分钟前', type: 'config' },
          { id: 3, action: '工具部署', user: 'dev', time: '30 分钟前', type: 'tool' },
          { id: 4, action: '系统备份', user: 'system', time: '1 小时前', type: 'system' },
        ]);
        
        setLoading(false);
      }, 1000);
    } catch (error) {
      console.error('加载仪表板数据失败:', error);
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadDashboardData();
  }, [loadDashboardData]);

  const getActivityTypeColor = (type: string) => {
    switch (type) {
      case 'login': return 'green';
      case 'config': return 'blue';
      case 'tool': return 'orange';
      case 'system': return 'purple';
      default: return 'default';
    }
  };

  const handleRefresh = () => {
    setLoading(true);
    loadDashboardData();
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>
          <DashboardOutlined /> 仪表板
        </Title>
        <Text type="secondary">
          欢迎回来，{user?.username}！这里是系统概览。
        </Text>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={stats.totalUsers}
              prefix={<UserOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="活跃工具"
              value={stats.activeTools}
              prefix={<ToolOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="系统健康度"
              value={stats.systemHealth}
              suffix="%"
              prefix={<CheckCircleOutlined />}
              precision={1}
              loading={loading}
              valueStyle={{ color: stats.systemHealth > 95 ? '#3f8600' : '#cf1322' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="今日任务"
              value={stats.dailyTasks}
              prefix={<SyncOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        {/* 快捷操作 */}
        <Col xs={24} lg={12}>
          <Card
            title="快捷操作"
            extra={<Button icon={<SyncOutlined />} onClick={handleRefresh} loading={loading}>刷新</Button>}
          >
            <Row gutter={[8, 8]}>
              <Col span={12}>
                <Button
                  type="primary"
                  icon={<ToolOutlined />}
                  size="large"
                  style={{ width: '100%', height: '60px' }}
                >
                  工具管理
                </Button>
              </Col>
              <Col span={12}>
                <Button
                  icon={<SettingOutlined />}
                  size="large"
                  style={{ width: '100%', height: '60px' }}
                >
                  配置管理
                </Button>
              </Col>
              {isAdmin && (
                <>
                  <Col span={12}>
                    <Button
                      icon={<UserOutlined />}
                      size="large"
                      style={{ width: '100%', height: '60px' }}
                    >
                      用户管理
                    </Button>
                  </Col>
                  <Col span={12}>
                    <Button
                      icon={<DashboardOutlined />}
                      size="large"
                      style={{ width: '100%', height: '60px' }}
                    >
                      系统监控
                    </Button>
                  </Col>
                </>
              )}
            </Row>
          </Card>
        </Col>

        {/* 最近活动 */}
        <Col xs={24} lg={12}>
          <Card title="最近活动" loading={loading}>
            <List
              dataSource={recentActivities}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    title={
                      <Space>
                        <Text>{item.action}</Text>
                        <Tag color={getActivityTypeColor(item.type)}>{item.type}</Tag>
                      </Space>
                    }
                    description={`${item.user} · ${item.time}`}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {/* 系统状态 */}
      <Row style={{ marginTop: 16 }}>
        <Col span={24}>
          <Card title="系统状态">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Alert
                message="系统运行正常"
                description="所有核心服务运行稳定，无异常报告。"
                type="success"
                showIcon
                action={
                  <Button size="small" ghost>
                    查看详情
                  </Button>
                }
              />
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;
